package method

import (
	"encoding/json"

	"fmt"
	"os"

	"next-ppt/sql"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type serverConfig struct {
	Database Database `json:"database"`
	Server   Server   `json:"server"`
	Admin    Admin    `json:"admin"`
}

type Database struct {
	Host     string `json:"host"`
	Port     string `json:"port"`
	User     string `json:"user"`
	Password string `json:"password"`
	Database string `json:"database"`
}

type Server struct {
	Port           string `json:"port"`
	ServerName     string `json:"server_name"`
	Icon           string `json:"icon"`
	TokenKey       string `json:"token_key"`
	ExpireTime     int64  `json:"expire_time"`
	PptDownloadNum int64  `json:"ppt_download_num"`
	PptPageShowNum int    `json:"ppt_page_show_num"`
}

type Admin struct {
	Name     string `json:"name"`
	Password string `json:"password"`
	Email    string `json:"email"`
	Phone    string `json:"phone"`
	Avatar   string `json:"avatar"`
}

var Db *gorm.DB
var Config serverConfig

func init() {
	content, err := os.ReadFile("./config.json")
	if err != nil {
		Exit("读取配置文件失败", err)
		return
	}
	fmt.Println("读取配置文件成功")
	err = json.Unmarshal(content, &Config)
	if err != nil {
		Exit("解析配置文件失败", err)
		return
	}
	fmt.Println("解析配置文件成功")
	if Config.Server.ServerName[len(Config.Server.ServerName)-1] != '/' {
		Config.Server.ServerName += "/"
	}

	dirList := []string{"./ppt", "./img", "./pptImg", "./pptReviews", "./app"}
	for i := 0; i < len(dirList); i++ {
		err := CreateDirIfNotExists(dirList[i])
		if err != nil {
			Exit("创建目录失败", err)
			return
		}
	}
	dsn := Config.Database.User + ":" + Config.Database.Password + "@tcp(" + Config.Database.Host + ":" + Config.Database.Port + ")/" + Config.Database.Database + "?charset=utf8mb4&parseTime=True&loc=Local"
	var dberr error
	Db, dberr = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		Exit("数据库连接失败", dberr)
		return
	}
	fmt.Println("数据库连接成功")
	Db.AutoMigrate(&sql.PptFiles{}, &sql.PptList{}, &sql.DownloadList{}, &sql.User{}, &sql.Token{})
}

func Exit(Type string, Msg interface{}) {
	fmt.Println(Type, Msg)
	fmt.Printf("按回车键退出程序 ...")
	endKey := make([]byte, 1)
	os.Stdin.Read(endKey)
}

func CreateDirIfNotExists(dirPath string) error {
	// 检查目录是否存在
	if _, err := os.Stat(dirPath); os.IsNotExist(err) {
		// 创建一个新的目录
		err = os.MkdirAll(dirPath, 0755) // 0755 是目录的默认权限
		if err != nil {
			return err
		}
	}
	return nil
}

// 字节的单位转换 保留两位小数
func FormatFileSize(fileSize int64) (size string) {
	if fileSize < 1024 {
		//return strconv.FormatInt(fileSize, 10) + "B"
		return fmt.Sprintf("%.2fB", float64(fileSize)/float64(1))
	} else if fileSize < (1024 * 1024) {
		return fmt.Sprintf("%.2fKB", float64(fileSize)/float64(1024))
	} else if fileSize < (1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fMB", float64(fileSize)/float64(1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))
	} else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
		return fmt.Sprintf("%.2fPB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
	}
}
